package com.evanp.pay.service;

import com.alipay.easysdk.factory.Factory;
import com.alipay.easysdk.kernel.Config;
import com.alipay.easysdk.kernel.util.ResponseChecker;
import com.alipay.easysdk.payment.common.models.AlipayTradeFastpayRefundQueryResponse;
import com.alipay.easysdk.payment.common.models.AlipayTradeQueryResponse;
import com.alipay.easysdk.payment.common.models.AlipayTradeRefundResponse;
import com.alipay.easysdk.payment.page.models.AlipayTradePagePayResponse;
import com.evanp.pay.config.AlipayConfig;
import com.evanp.pay.util.ResBuilder;
import com.google.gson.Gson;
import org.slf4j.Logger;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.Map;


@Service
public class AlipayServiceImpl implements AlipayService{

    @Resource
    Logger logger;

    @Resource
    Gson gson;

    @Resource
    AlipayConfig alipayConfig;

    @Override
    public String webPagePay(String subject, String outTradeNo, String totalAmount) {
        try {
            AlipayTradePagePayResponse response = Factory.Payment.Page().pay(subject,outTradeNo,totalAmount,alipayConfig.returnUrl);
            if (ResponseChecker.success(response)){
                logger.info("支付调用成功");
                return response.getBody();
            } else {
                logger.error("支付调用失败: ".concat(response.getBody()));
                return "支付调用失败";
            }
        } catch (Exception e){
            logger.error("支付调用异常: ".concat(e.getMessage()));
            return "支付调用异常";
        }
    }

    @Override
    public Map queryTrade(String oid) {
        Map<String,Object> data = new HashMap<>();
        try {
            AlipayTradeQueryResponse response = Factory.Payment.Common().query(oid);
            if ("10000".equals(response.getCode())){

                Map body = gson.fromJson(response.getHttpBody(), Map.class);
                data.put("result", body.get("alipay_trade_query_response"));
                return ResBuilder.ok("支付查询成功", 0, data);
            } else {
                data.put("result", response.getSubMsg());
                System.out.println("支付查询失败: " + response.getSubMsg());
                return ResBuilder.fail("支付查询失败", 0, data);
            }
        } catch (Exception e){
            logger.error("支付查询异常: ".concat(e.getMessage()));
            return ResBuilder.bad("支付查询异常");
        }

    }

    @Override
    public Map refund(String oid, String money) {
        try {
            AlipayTradeRefundResponse response = Factory.Payment
                    .Common()
                    // 调用交易退款(商家订单号, 退款金额默认整单)
                    .refund(oid, money);
            if ("Y".equals(response.getFundChange())) {
                Map<String,String> data = new HashMap<>();
                data.put("refund_total", response.getRefundFee());
                return ResBuilder.ok("退款成功", 0, data);
            } else {
                Map<String,String> data = new HashMap<>();
                switch (response.getSubCode()) {
                    case "SYSTEM_ERROR": {
                        data.put("reason", "系统错误");
                    }
                    case "ACQ.SELLER_BALANCE_NOT_ENOUGH": {
                        data.put("reason", "商家余额不足");
                    }
                    case "ACQ.REFUND_AMT_NOT_EQUAL_TOTAL": {
                        data.put("reason", "退款金额超限");
                    }
                    default: {
                        data.put("reason", response.getSubMsg());
                    }
                }

                return ResBuilder.fail("退款失败", 0, data);
            }
        } catch (Exception e) {
            e.printStackTrace();
            return ResBuilder.bad("退款异常");
        }
    }

    @Override
    public Map queryRefund(String oid) {
        try {
            AlipayTradeFastpayRefundQueryResponse response = Factory.Payment.Common().queryRefund(oid,oid);
            if ("REFUND_SUCCESS".equals(response.getRefundStatus())){
                return ResBuilder.ok("退款成功", 0);
            } else {
                Map<String,String> data = new HashMap<>();
                data.put("reason", response.getSubMsg());
                return ResBuilder.fail("退款失败", 0, data);
            }
        } catch (Exception e) {
            e.printStackTrace();
            return ResBuilder.bad("查询退款异常");
        }
    }
}
